package org.geometerplus.zlibrary.ui.android.view.animation;

import android.graphics.Bitmap;
import android.graphics.Canvas;

import com.example.administrator.fangbook.read.view.readView.ZLAndroidWidget;

import org.geometerplus.zlibrary.core.view.ZLViewEnums;

/**
 * 阅读页面承载（bitmap）管理类
 */
public class BitmapManager {
    private final int SIZE = 2;
    /**
     * 当前缓存的页面
     */
    private final Bitmap[] mBitmaps = new Bitmap[SIZE];
    /**
     * 当前缓存的页面坐标
     */
    private final ZLViewEnums.PageIndex[] mIndexes = new ZLViewEnums.PageIndex[SIZE];

    private final ZLAndroidWidget mWidget;

    private int mWidth;
    private int mHeight;

    public BitmapManager(ZLAndroidWidget mReadView) {
        this.mWidget = mReadView;
    }


    public void setSize(int w, int h) {
        if (mWidth != w || mHeight != h) {
            mWidth = w;
            mHeight = h;
        }
    }

    /**
     * 根据坐标获取当前bitmap
     *
     * @param index
     * @return
     */
    public Bitmap getBitmapCached(ZLViewEnums.PageIndex index) {
        for (int i = 0; i < SIZE; ++i) {
            if (index == mIndexes[i] && mBitmaps[i] != null) {
                return mBitmaps[i];
            }
        }
        return null;
    }

    /**
     * 准备当前页面信息
     */
    public void prepareCurrentPagePaintInfo() {
        drawOnBitmap(ZLViewEnums.PageIndex.current);
    }

    /**
     * 准备好bitmap，交给view把信息绘制到bitmap上
     *
     * @param index
     */
    private void drawOnBitmap(ZLViewEnums.PageIndex index) {
        Bitmap emptyBitmap = getEmptyBitmap(index);
        if (emptyBitmap != null) {
            mWidget.drawOnBitmap(emptyBitmap, index);
        }
    }

    /**
     * 根据页面坐标，获取一个闲置的bitmap
     *
     * @param index
     * @return
     */
    private Bitmap getEmptyBitmap(ZLViewEnums.PageIndex index) {
        for (int i = 0; i < SIZE; i++) {
            //缓存的坐标和传入相同，缓存的bitmap不等于null并且没有被回收
            if (index == mIndexes[i] && mBitmaps[i] != null && !mBitmaps[i].isRecycled()) {
                return mBitmaps[i];
            }
        }
        for (int i = 0; i < SIZE; i++) {
            if (mIndexes[i] == null || mIndexes[i] != ZLViewEnums.PageIndex.current) {
                mIndexes[i] = index;
                if (mBitmaps[i] == null || mBitmaps[i].isRecycled()) {
                    mBitmaps[i] = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_4444);
                }
                return mBitmaps[i];
            }

        }
        return null;
    }
}
